package com.zhouwr.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.jexl3.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: forallcn-iotps
 * @description: DyMethodUtil
 * @author: zhouwr
 * @create: 2021-03-03 21:22
 * @version：1.0
 **/
@Slf4j
public class DyMethodUtil {
    public static Object invokeMethod(String jexlExp, Map<String, Object> dataMap) {
        JexlEngine jexl = new JexlBuilder().create();
        JexlExpression e = jexl.createExpression(jexlExp);
        // 创建context，用于传递参数
        JexlContext jc = new MapContext();
        dataMap.forEach(jc::set);

        // 执行表达式
        Object evaluate = e.evaluate(jc);
        log.info("{} => {} => {}", dataMap, jexlExp, evaluate);
        return evaluate;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("temperature", 24);
        String expression = "temperature>=22&&temperature<30";
        Object code = invokeMethod(expression, map);
        System.err.println(code);
    }
}
